//
//  CYPersonalDetailsVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/28.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYPersonalDetailsVController.h"
#import "CYUser.h"
#import "CYMeHttpTool.h"
#import "CYEscape.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImageView+WebCache.h"
#import "CYHttpTool.h"
#import "CYLoginHttpTool.h"
#import "CYURL.h"
#import "UIButton+WebCache.h"
#import "CYJumpsTool.h"
#import "CYNavigationVController.h"
#import "CYJsonInfo.h"
#import "UIImage+DY.h"
#import "CYCardIDCheckVC.h"
#import "CYGetdealCodeVC.h"
#import "CYModifyPasswordVC.h"
#import "CYBankcardBandTableViewController.h"
#import "CYbankcarddetailVC.h"
#import "UIAlertView+Block.h"
#import "CYShimingbangkaVC.h"
#import "CYShimingBangkaVCTableViewController.h"


static const NSInteger CYLogoutAlertTag = 55;
static const NSInteger CYChangeNickNameAlertTag = 56;


@interface CYPersonalDetailsVController ()<UIAlertViewDelegate, UITextFieldDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nickNameTF;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *userClassifyLabel;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UIButton *headBtn;
@property (weak, nonatomic) IBOutlet UIButton *examineBtn;
@property (weak, nonatomic) IBOutlet UILabel *dcstatuesLab;


@property (strong, nonatomic) CYUser *user;
@property (strong, nonatomic) NSString *headPic;
@property (strong, nonatomic) CYUser *userShowData;

@property (weak, nonatomic) IBOutlet UILabel *bankcardStatuesLab;

@property (nonatomic, strong) NSString *status;

@property (weak, nonatomic) IBOutlet UIButton *loginoutBtn;

@property (weak, nonatomic) IBOutlet UILabel *userTypeLab;
@property (weak, nonatomic) IBOutlet UILabel *newdealcodeLab;
@property (nonatomic,strong) UIView * writeView;
@property (nonatomic,strong) UIView * shituview;
@property (nonatomic,strong) NSString * weixinname;

@end

@implementation CYPersonalDetailsVController

- (void)setUserShowData:(CYUser *)userShowData {
    CYUser *user = [CYLoginHttpTool userData].user;
    _userShowData = userShowData;
    self.phoneLabel.text = userShowData.phone;
    self.statusLabel.text = userShowData.certificateExamineStatusText;
     if (user.certificateExamineStatus.intValue == 2) {
          _dcstatuesLab.text = @"已实名";
          _dcstatuesLab.textColor = [UIColor lightGrayColor];
     }else{
          _dcstatuesLab.text = @"未实名";
     }
    if (user.certificateExamineStatus && ![user.certificateExamineStatus isKindOfClass:[NSNull class]]){
    
    if (!userShowData.isShowExamineBtn) {
        self.examineBtn.hidden = YES;
    }
}
    //设置初始化数据
    if (self.user.nickName) {
        self.nickNameTF.text = self.user.nickName;
    }
    //头像有值的话设置头像边框
    if (self.user.headPic && ![self.user.headPic isEqualToString:@""]) {
        [self setupHeadPicProperty];
        [self.headBtn sd_setImageWithURL:CYURLWithUserService(self.user.headPic) forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"complete_profile_men_sel"]];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self userDefaults];
     _loginoutBtn.layer.cornerRadius = 5.0f;
    self.navigationItem.title = @"个人信息";
//    [self setupLogout];
    [self getpercent];
     [self loaddealcode];
     [self setbankcard];
    self.headBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
}

- (IBAction)loginoutClick:(id)sender {
     [self logout];
     
}
- (IBAction)newchangeBCClick:(id)sender {
     CYUser *user = [CYLoginHttpTool userData].user;
     if (user) {
          if ([user.certificateExamineStatus  longLongValue] == 2 ) {
               if (_status.intValue != 1) {
                    CYBankcardBandTableViewController *bankcd = [CYBankcardBandTableViewController le_loadFromStoryBoard:[CYJumpsTool mainSB]];
                    bankcd.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:bankcd animated:YES];
                    return;
               }
               
               CYbankcarddetailVC *bacd = [[CYbankcarddetailVC alloc]init];
               bacd.hidesBottomBarWhenPushed = YES;
               [self.navigationController pushViewController:bacd animated:YES];
               
          }else{
               UIAlertView *txaler = [[UIAlertView alloc]initWithTitle:@"您需要进行实名绑卡!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
               [txaler show];
//               [txaler showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
//                    if (buttonIndex == 1) {
//                         
//                         CYCardIDCheckVC *cardcheck = [[CYCardIDCheckVC alloc]init];
//                         
//                         cardcheck.hidesBottomBarWhenPushed = YES;
//                         [self.navigationController pushViewController:cardcheck animated:YES];
//                    }
//               }];
          }
          
          // [txaler showAlertViewWithCompleteBlock:^(NSInteger buttonIndex)
          
     }else{
          [CYJumpsTool jumpToLogin:self];
     }

}


//
-(void)setbankcard{
     CYUser *user = [CYLoginHttpTool userData].user;
     [CYHttpTool postWithURL:[CYURL shared].getBandCardStatus params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsoninfo.isSuccess) {
               NSDictionary *data = jsoninfo.data;
               _status = [data valueForKey:@"status"];
               if (_status.intValue == 1) {
                    _userClassifyLabel.text = @"已绑定";
                    
               }else{
                    _userClassifyLabel.text = @"未绑定";
               }
               
          }
     } failure:^(NSError *error) {
          CYLog(@"error = %@",error);
          _bankcardStatuesLab.text = @"加载失败";
     }];
     
}

//
- (IBAction)bankcardClick:(id)sender {
     
     CYModifyPasswordVC *modify = [[CYModifyPasswordVC alloc] init];
     [self.navigationController pushViewController:modify animated:YES];
     
     
}

- (IBAction)shimingCheckClick:(id)sender {
     
     
}

//修改密码
- (IBAction)changePasswordClick:(id)sender {
     
     CYGetdealCodeVC *dealcode = [[CYGetdealCodeVC alloc]init];
     [self.navigationController pushViewController:dealcode animated:YES];

//     CYModifyPasswordVC *modify = [[CYModifyPasswordVC alloc] init];
//     [self.navigationController pushViewController:modify animated:YES];

}

-(void)loaddealcode{
     
     CYUser *user = [CYLoginHttpTool userData].user;
     [CYHttpTool postWithURL:[CYURL shared].getDealCodeStatus params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
          CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
          NSString  *type = jsonInfo.data;
          if (type.intValue == 1) {
               _newdealcodeLab.text = @"已设置";
          }else{
               _newdealcodeLab.text = @"未设置";
          }
     } failure:^(NSError *error) {
          CYLog(@"error = %@",error);
          _dcstatuesLab.text = @"网络错误，加载失败";
     }];

}

-(void)getpercent{
     CYUser *user = [CYLoginHttpTool userData].user;
     [CYHttpTool postWithURL:[CYURL shared].iosImageCompress params:@{} success:^(id json) {
          CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];

          NSNumber *a = jsoninfo.data;
          user.percent = a;
          CYLog(@"a = %@",a);
          [CYLoginHttpTool updateUserData:user];
          
     } failure:^(NSError *error) {
          
     }];
     
     
}

- (IBAction)completeClick:(id)sender {

     CYCardIDCheckVC *cardcheck = [[CYCardIDCheckVC alloc]init];
     
     [self.navigationController pushViewController:cardcheck animated:YES];
     
}

//修改手机号码弹出视图的点击方法
- (IBAction)ModifyPromptOnclicked:(UIButton *)sender {
     
     UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
     bgView.backgroundColor = [UIColor grayColor];
     bgView.alpha = 0.8;
     self.writeView = bgView;
     self.writeView.hidden = NO;
     [[UIApplication sharedApplication].keyWindow addSubview:_writeView];
     
     _shituview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 260, 290)];
     _shituview.layer.cornerRadius = 5;
     _shituview.layer.masksToBounds = YES;
     _shituview.center = self.view.center;
     _shituview.backgroundColor = [UIColor whiteColor];
     [[UIApplication sharedApplication].keyWindow addSubview:_shituview];
     [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_shituview];
     UILabel * tishiLabel = [[UILabel alloc] init];
     tishiLabel.frame = CGRectMake(_shituview.frame.size.width /2 - 23, 5, 40, 20);
     tishiLabel.text = @"提示";
     tishiLabel.textAlignment = NSTextAlignmentCenter;
     tishiLabel.font = [UIFont systemFontOfSize:16.0];
     [_shituview addSubview:tishiLabel];
     
     UILabel * yonghuLB = [[UILabel alloc] init];
     yonghuLB.frame = CGRectMake(10, 30, _shituview.frame.size.width - 20, 15);
     yonghuLB.text = @"尊敬的用户您好,修改手机号码成功后,";
     yonghuLB.numberOfLines = 0;
     yonghuLB.font = [UIFont systemFontOfSize:14.0];
     UILabel * xuyaoLB = [[UILabel alloc] init];
     xuyaoLB.frame = CGRectMake(10, 50, _shituview.frame.size.width - 20, 15);
     xuyaoLB.text = @"需要重新完成运营商认证,步骤如下:";
     xuyaoLB.numberOfLines = 0;
     xuyaoLB.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:yonghuLB];
     [_shituview addSubview:xuyaoLB];
     UILabel * addLabel = [[UILabel alloc] init];
     addLabel.frame = CGRectMake(10, 75, _shituview.frame.size.width - 20, 15);
     addLabel.text = @"1.添加微信公众号：";
     addLabel.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:addLabel];
     UILabel * tianxiaLb = [[UILabel alloc] init];
     tianxiaLb.frame = CGRectMake(10, 95, 120, 15);
     tianxiaLb.text = @"天下无赖诚信联盟";
     
     _weixinname = tianxiaLb.text;
     tianxiaLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:tianxiaLb];
     
     UIButton * fuzhiBtn = [[UIButton alloc] initWithFrame:CGRectMake(tianxiaLb.frame.size.width + 50, 90, 40, 25)];
     fuzhiBtn.backgroundColor = [UIColor grayColor];
     fuzhiBtn.layer.cornerRadius = 3;
     fuzhiBtn.layer.masksToBounds = YES;
     [fuzhiBtn setTitle:@"复制" forState:UIControlStateNormal];
     [fuzhiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     fuzhiBtn.titleLabel.font = [UIFont systemFontOfSize:16];
     [fuzhiBtn addTarget:self action:@selector(fuzhiDClicked) forControlEvents:UIControlEventTouchUpInside];
     [_shituview addSubview:fuzhiBtn];
     
     UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(10, 120, _shituview.frame.size.width - 20, 1)];
     lineView.backgroundColor = [UIColor grayColor];
     [_shituview addSubview:lineView];
     
     UILabel * twoLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 130, _shituview.frame.size.width - 20, 15)];
     twoLabel.text = @"2.给“天下无赖诚信联盟”留言";
     twoLabel.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:twoLabel];
     
     UILabel * liuyanLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 150, _shituview.frame.size.width - 20, 15)];
     liuyanLb.text = @"留言示例：";
     liuyanLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:liuyanLb];
     UILabel * shoujiLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 175, _shituview.frame.size.width - 20, 15)];
     shoujiLb.text = @"3.手机号码更换申请";
     shoujiLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:shoujiLb];
     
     UILabel * jiuLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 195, _shituview.frame.size.width - 20, 15)];
     jiuLb.text = @"旧号码：13****xxx";
     jiuLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:jiuLb];
     
     UILabel * xinLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 215, _shituview.frame.size.width - 20, 15)];
     xinLb.text = @"新号码：15****xxx";
     xinLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:xinLb];
     
     UIView * lineTwoView = [[UIView alloc] initWithFrame:CGRectMake(10, 240, _shituview.frame.size.width - 20, 1.0f)];
     lineTwoView.backgroundColor = [UIColor grayColor];
     [_shituview addSubview:lineTwoView];
     
     UIButton * quxiaoBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 250, _shituview.frame.size.width - 40, 30)];
     quxiaoBtn.backgroundColor = [UIColor colorWithRed:111/255.0 green:185/255.0 blue:87/255.0 alpha:1];
     quxiaoBtn.layer.cornerRadius = 3;
     quxiaoBtn.layer.masksToBounds = YES;
     [quxiaoBtn setTitle:@"取消" forState:UIControlStateNormal];
     [quxiaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     [quxiaoBtn addTarget:self action:@selector(quxiaoBtnOclicked) forControlEvents:UIControlEventTouchUpInside];
     [_shituview addSubview:quxiaoBtn];
}

- (void)fuzhiDClicked {
     UIPasteboard *pab = [UIPasteboard generalPasteboard];
     [pab setString:_weixinname];
     if (pab == nil) {
          [MBProgressHUD showError:@"复制失败"];
          
     }else
     {
          [MBProgressHUD showSuccess:@"已复制"];
          
     }
     
}

- (void)quxiaoBtnOclicked {
     _writeView.hidden = YES;
     _shituview.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
     [_writeView removeFromSuperview];
     [_shituview removeFromSuperview];
}

/**
 *  获取用户数据以及设置初始化数据
 */
- (void)userDefaults {
    self.user = [CYLoginHttpTool userData].user;
    if (!self.user) {
        [self.navigationController popViewControllerAnimated:YES];
        [CYJumpsTool jumpToLogin:self];
        return;
    }
    self.userShowData = self.user;
    //从服务器获取最新用户信息
    [self userNewData];
}

/**
 *  从服务器获取最新用户信息
 */
- (void)userNewData {
//    NSDictionary *params = @{@"userId": self.user.userId, @"token": self.user.token};
//    [CYMeHttpTool userWithParams:params success:^(CYUser *user) {
//    [CYLoginHttpTool updateUserData:user];
//        self.user = user;
//        self.userShowData = user;
//    } failure:^(NSError *error) {
//        CYLog(@"从服务器获取最新用户信息失败：%@", error);
//    }];
    [CYMeHttpTool getUserStatusForSuccess:^(CYUser *user) {
        self.user = user;
        self.userShowData = user;
    } failure:^(NSString *message, BOOL isLogin) {
        if (!isLogin) {
            [self.navigationController popViewControllerAnimated:YES];
            [CYLoginHttpTool logoutWithController:self];
        }
        [MBProgressHUD showError:message];
    }];
}

/**
 *  设置登出操作
 */
- (void)setupLogout {
    if (self.pushType == CYPushTypePresent) {
        UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
        btn.tintColor = [UIColor blackColor];
        self.navigationItem.rightBarButtonItem = btn;
    } else {
        UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithTitle:@"登出" style:UIBarButtonItemStylePlain target:self action:@selector(logout)];
        btn.tintColor = [UIColor blackColor];
        self.navigationItem.rightBarButtonItem = btn;
    }
}

/**
 *  修改头像
 */
- (IBAction)changePortrait:(id)sender {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

- (void)logout {
    UIAlertView *logoutAlert = [[UIAlertView alloc]initWithTitle:@"确认退出当前账号？" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    logoutAlert.tag = CYLogoutAlertTag;
    [logoutAlert show];
}

- (void)cancel {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        if (alertView.tag == CYLogoutAlertTag) {
            //登出后清除本地归档信息
            [CYLoginHttpTool isClearUserData];
            //登出后清除本地归档信息
            NSUserDefaults *deft = [NSUserDefaults standardUserDefaults];
            [deft removeObjectForKey:CYUserNameKey];
            [deft removeObjectForKey:CYPasswordKey];
            [deft synchronize];
            
            //跳转到Main
            [CYJumpsTool jumpToMain:self.view];
        }else if (alertView.tag == CYChangeNickNameAlertTag) {
            
            [MBProgressHUD showMessage:@"修改中..." toView:self.view];
            [self updateUser];
        }
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            controller.allowsEditing = YES;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller animated:YES completion:^(void){
            }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            controller.allowsEditing = YES;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller animated:YES completion:^(void){
            }];
        }
    }

}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        //对图片进行压缩
//        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        UIImage *portraitImg = [info objectForKey:UIImagePickerControllerEditedImage];
//        CYLog(@"oldH:%f---oldW:%f", portraitImg.size.height, portraitImg.size.width);
//        UIImage *newImage = [UIImage imageWithImage:portraitImg scaledToSize:(CGSize){200, 200}];
//        CYLog(@"height---%f, with---%f", newImage.size.height, newImage.size.width);
        CGSize size = CGSizeMake(200, 200);
        NSData *cutData = [UIImage imageDataWithImage:portraitImg scaledToSize:size];
        //头像上传
        [MBProgressHUD showMessage:@"头像上传中..." toView:self.view];
        [self uploadHeadPic:[UIImage imageWithData:cutData]];
        
        [self setupHeadPicProperty];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  头像上传
 */
- (void)uploadHeadPic:(UIImage *)image {
    [CYHttpTool postWithURL:[CYURL updateHeadPicrPath] params:nil image:image success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        //上传成功更新头像访问路径
        if (jsonInfo.isSuccess) {
            self.headPic = jsonInfo.message;
            //上传成功设置显示图片
            [self.headBtn setImage:image forState:UIControlStateNormal];
            [self updateUser];
        }else {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:jsonInfo.message];
        }
    } failure:^(NSError *error) {
        CYLog(@"头像上传服务器连接失败：%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        switch (error.code) {
            case CYErrorCodeOverTime:
            [MBProgressHUD showError:CYServerConnectTimeOver];
            break;
            
            default:
            [MBProgressHUD showError:@"网络错误，请重新上传"];
            break;
        }
    } uploadProgress:nil];
}

/**
 *  更新用户信息
 */
- (void)updateUser {
    if (self.user) {
        CYUser *user = self.user;
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"userId"] = user.userId;
        params[@"token"] = user.token;
        if (self.headPic) {
            params[@"headPic"] = self.headPic;
        }
        if (self.nickNameTF.text) {
            params[@"nickName"] = self.nickNameTF.text;
        }
        
        [CYMeHttpTool updateUserWithParams:params success:^(id json) {
//            CYLog(@"用户更新json:%@", json);
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                //返回的json是更新后的最新用户信息
                CYUser *user = [CYUser objectWithKeyValues:jsonInfo.data];
                //将最新的用户信息保存到沙盒
                [CYLoginHttpTool updateUserData:user];
                //更新完成发送通知：用户信息已更新。个人中心进行监听
                NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                if (user.nickName) {
                    userInfo[CYChangedNickName] = user.nickName;
                }
                if (user.headPic) {
                    userInfo[CYChangedHeadPic] = user.headPic;
                }
                if (!user.nickName && !user.headPic) {
                    userInfo = nil;
                }
                [CYNotificationCenter postNotificationName:CYNickNameDidChangeNotification object:nil userInfo:userInfo];
                
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:@"修改成功"];
            } else if(jsonInfo.isNoLogin) {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:@"用户信息已过期，请重新登录"];
                [CYLoginHttpTool logout];
                [CYJumpsTool jumpToLogin:self];
            } else {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:jsonInfo.message];
            }
        } failure:^(NSError *error) {
            CYLog(@"更新用户信息服务器连接失败：%@", error);
            [MBProgressHUD hideHUDForView:self.view];
            switch (error.code) {
                case CYErrorCodeOverTime:
                [MBProgressHUD showError:CYServerConnectTimeOver];
                break;
                
                default:
                [MBProgressHUD showError:@"网络错误，请重新上传"];
                break;
            }
        }];
    }
}

//交易密码
- (IBAction)dealCodeClick:(id)sender {
     
     CYUser *user = [CYLoginHttpTool userData].user;
     
     if (user.certificateExamineStatus.intValue == 2) {
          CYAlertView(@"您已进行过认证！");
          return;
     }else{
          
          CYCardIDCheckVC *cardcheck = [[CYCardIDCheckVC alloc]init];
          cardcheck.hidesBottomBarWhenPushed = YES;
          [self.navigationController pushViewController:cardcheck animated:YES];
          
     }
}

#pragma mark - UITextFieldDelegate
/**
 *  return键监听
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length && self.user && ![self.user.nickName isEqualToString:self.nickNameTF.text]) {
        UIAlertView *logoutAlert = [[UIAlertView alloc]initWithTitle:@"确认修改用户名？" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        logoutAlert.tag = CYChangeNickNameAlertTag;
        [logoutAlert show];
    }
    [textField resignFirstResponder];
    return YES;
}

/**
 *  设置头像边框
 */
- (void)setupHeadPicProperty {
    self.headBtn.imageView.layer.cornerRadius = 30.0;
    self.headBtn.imageView.layer.masksToBounds = YES;
    self.headBtn.imageView.layer.borderColor = [CYNaviThemeColor CGColor];
    self.headBtn.imageView.layer.borderWidth = 2.5;
}

#pragma mark - camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view.window endEditing:YES];
}

- (void)dealloc {
    CYLog(@"个人信息销毁");
}

@end
